package com.mock.ai.utils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class TTSUtils {

    private static final String APP_KEY = "5cc28579f0e33a2e";     // 您的应用ID
    private static final String APP_SECRET = "fFWwU4Gxqe4Xe8qdu5tGgvXGr9PGsVlr";  // 您的应用密钥

    // 合成音频保存路径, 例windows路径：PATH = "C:\\tts\\media.mp3";
    private static final String PATH = "D:\\tts\\media.mp3";


    public static String tts(String language) throws NoSuchAlgorithmException, IOException {
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(language);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/ttsapi", null, params, "audio");
        // 打印返回结果
        if (result != null) {
            String path = FileUtil.saveFile(PATH, result, false);
            System.out.println("save path:" + path);
            return path;
        }
        // System.exit(1);
        return null;
    }

    private static Map<String, String[]> createRequestParams(String language) {
        /*
         * note: 将下列变量替换为需要请求的参数
         */
        String q = language;
        String voiceName = "youxiaoxun";
        String format = "mp3";

        return new HashMap<String, String[]>() {{
            put("q", new String[]{q});
            put("voiceName", new String[]{voiceName});
            put("format", new String[]{format});
        }};
    }
}
